<template>
  <div>
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="from"
      :list="formList"
      :formType="type"
      @formChange="changeHandle"
      :isSubmitBtn="false"
      labelWidth="110" />
    <BreakSpace v-if="type!=='add'" label="变更履历" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable v-if="type!=='add'"
     ref="table"
     :columns="columns"
     :fetchapi="fetchApi"
     :dataSource="gethistroyList"
     :params="fetchParams"
     :datakey="'records'"
     :isSelectColumn="false"
     :onRowSelectChange="selectChange"
     columnsRef="jzySeries"
     :onColumnsChange="columns => this.columns = columns"
    >
    </FilterTable>
    <div class="dialogBottmView" >
      <el-button v-if="type!=='detil'&& type!=='sh'" @click="closeDialogTop">取 消</el-button>
      <el-button v-if="type==='detil'|| type==='sh'" @click="back">返 回</el-button>
      <!-- 不校验保存 -->
      <el-button v-if="type!=='sh'&& type!=='detil'" @click="saveDialog('BC')" :loading="saveLoading"   :disabled="isSave" type="primary">保存</el-button>
      <el-button v-if="type!=='sh'&& type!=='detil'" @click="saveDialog('TB')" :loading="saveLoading"   :disabled="isSave" type="primary">提报</el-button>
      <el-button v-if="type==='sh'" @click="saveDialog('TG')" :loading="saveLoading"   :disabled="isSave" type="primary">审核通过</el-button>
      <el-button v-if="type==='sh'" @click="saveDialog('BH')" :loading="saveLoading"   :disabled="isSave" type="primary">审核驳回</el-button>
    </div>
  </div>
</template>

<script>
  import { dictionary } from '@/utils/dictMixin';
  import { region } from '@/api/cms-common/region';
  import { dosave, doupdate, getHistorylist,getdealer } from '@/api/part/accessories/index';
  import { getCurrentUser } from '@/api/cms-api/origin/construct/dealer';
  import _ from 'lodash';
  export default {
    name: "accessoriesAddressDLR",
    mixins: [dictionary,region],
    props: {
      type: {
        type: String,
        default: 'add'
      },
      rowData: {
        type: Object,
        default: () => ({})
      }
    },
    components:{
    },
    data() {
      this.saveData=null;
      return {
        gethistroyList:[],
        formList: this.createTopFilterList(),
        columns: this.createTableColumns(),
        fetchParams: {},
        fetchApi:this.history,
        isSave:false,
        records:'',
        saveLoading: false,
        visible:false,
        handleType:'',
        dialogTitle:'',
        companyCode:'',
        dealerName:'',
        dealerCode:''
      };
    },
    created() {
      this.getuser();
      this.initProvince();
      this.init();
    },
    methods: {
      getuser(){
        if (this.type==='add'){
          // 获取当前登录人信息
          getCurrentUser({}).then(response=>{
            console.info(response)
            this.formList.find(res=>res.fieldName=='xsjxhdm').initialValue=response.data.ownerCode // 经销商代码
            this.formList.find(res=>res.fieldName=='xsjxhmc').initialValue=response.data.dealerName // 经销商名称
            this.dealerCode = response.data.ownerCode //经销商ID
          })
        }
      },
      history(){
        getHistorylist(this.rowData.id).then(res=>{
          this.gethistroyList=res.data.records
        })
      },
      selectChange(val) {
        console.log('val', val);
        this.rowSelectData = val;
      },
      init(){
        console.info(this.rowData)
        if (this.type === 'edit'|| this.type === 'sh' || this.type === 'detil') { //点击编辑按钮拿到这一行的值,并赋值
          this.formList.forEach(x => {
            x.initialValue = this.rowData[x.fieldName];
          });
          //初始化所在市，区
          if(this.rowData['provinceid']){
            this.initCity(this.rowData['provinceid'],false);
          }
          if(this.rowData['cityid']){
            this.initTown(this.rowData['cityid'],false);
          }
        }
        if (this.type === 'edit'){
          //只有驳回状态的才能看到驳回原因
          this.formList.find(item => item.fieldName === 'xsbhyy'&& this.rowData['xtdjzt']===50031003).hidden=false
          this.formList.find(item => item.fieldName === 'xsbhyy'&& this.rowData['xtdjzt']===50031003).disabled=true
        }
        if (this.type === 'detil'){
          this.formList.forEach(x => {
            x.disabled=true
          }); //只有驳回状态的才能看到驳回原因
          this.formList.find(item => item.fieldName === 'xsbhyy'&& this.rowData['xtdjzt']===50031003).hidden=false
          this.formList.find(item => item.fieldName === 'xsbhyy'&& this.rowData['xtdjzt']===50031003).disabled=true
        }
        if (this.type === 'sh'){
          this.formList.forEach(x => {
            if (x.fieldName === 'xsbhyy'){
              x.initialValue=''
              x.disabled=false
            }else{
              x.disabled=true
            }
          });
        }
        if (this.type==="add"){
          this.formList.find(item => item.fieldName === 'xsjxhdm').initialValue=this.companyCode
          this.formList.find(item => item.fieldName === 'xsjxhmc').initialValue=this.dealerName;
        }
      },
      createTableColumns () {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '单据状态',
            dataIndex: 'xtdjzt',
            sorter: true,
            render: props => {    //编码转汉字
              return <span>{this.createDictText(props.row.xtdjzt, '5003')}</span>;
            }
          },
          {
            title: '申请类型',
            dataIndex: 'xssqlx',
            sorter: true,
            render: props => {    //编码转汉字
              return <span>{this.createDictText(props.row.xssqlx, '5002')}</span>;
            }
          },
          {
            title: '地址性质',
            dataIndex: 'xsdzxz',
            sorter: true,
            render: props => {    //编码转汉字
              return <span>{this.createDictText(props.row.xsdzxz, '5001')}</span>;
            }
          },
          { title: '省份', dataIndex: 'provinceId', sorter: true ,
            render: props => {
              return <span>{this.createRegionText(props.row.provinceid)}</span>;
            }
          },
          { title: '城市', dataIndex: 'cityId', sorter: true ,
            render: props => {
              return <span>{this.createRegionText(props.row.cityid)}</span>;
            }
          },
          { title: '县区', dataIndex: 'districtId', sorter: true ,
            render: props => {
              return <span>{this.createRegionText(props.row.districtid)}</span>;
            }
          },
          {
            title: '联系人',
            dataIndex: 'xtlxry',
            sorter: true,
          },
          {
            title: '联系电话',
            dataIndex: 'xtlxdh',
            sorter: true,
          },
          {
            title: '详细地址',
            dataIndex: 'xsxxdz',
            sorter: true,
          },
          {
            title: '创建人',
            dataIndex: 'createdBy',
            sorter: true,
          },
          {
            title: '创建时间',
            dataIndex: 'createdAt',
            sorter: true,
          },
          {
            title: '更新人',
            dataIndex: 'updatedBy',
            sorter: true,
          },
          {
            title: '更新时间',
            dataIndex: 'updatedAt',
            sorter: true,
          },
          {
            title: '是否有效',
            dataIndex: 'xtqybz',
            sorter: true,
            render: props => {    //编码转汉字
              return <span>{this.createDictText(props.row.xtqybz, '1004')}</span>;
            }
          },
          {
            title: '备注',
            dataIndex: 'xtbeiz',
            sorter: true,
          },
          {
            title: '驳回原因',
            dataIndex: 'xsbhyy',
            sorter: true,
          },
        ]
      },
      async saveDialog(item){
        this.$refs.from.excuteFormData(this.$refs.from.form);
        let base = this.$refs.from.form;
        if (item==='BC'){
          Object.assign(base,{xtdjzt:50031004,dealerCode:this.rowData.xsjxhdm}) // 保存
        }else if(item==='TB'){
          Object.assign(base,{xtdjzt:50031001,dealerCode:this.rowData.xsjxhdm}) //提报
        }else if(item==='TG'){
          Object.assign(base,{xtdjzt:50031002}) //审核通过
        }else if(item==='BH'){
          if (base.xsbhyy){
            Object.assign(base,{xtdjzt:50031003}) //审核驳回
          }else{
            this.$notify.error({title: '提示信息',message:'驳回原因不能为空!'});
            return false
          }
        }
        const err=this.$refs.from.SUBMIT_FORM();
        if (err===null){
          return false
        }else{
          // 判断该经销商是否已经维护了一个常用地址
          if (this.type==="add"){// 新增
            this.rowData.id=''
          }
          let dealerRes =  await getdealer(Object.assign(this.rowData,base,{type:this.type,dealerCode:this.rowData.xsjxhdm}))
          const response=dealerRes.data
          if (response.length>0){
            this.$notify.error({title: '提示信息',message:'一个经销商只能维护一个常用地址!'});
            return false
          }else{
            let res=''
            if (this.type==="add"){// 新增
              res = await dosave(base)
            }else{ //修改
              let date =Object.assign(this.rowData,base)
              res = await doupdate(date.id,date);
            }
            if (res.resultCode === 200) {
              this.$notify.success({title: '提示信息',message:'保存成功!'});
              // 重新加载
              this.closeDialog();
            }else {
              this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
              this.closeDialog();
            }
          }
        }
      },
      closeDialogTop(){
        this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.closeDialog('closeDialog');
          })
      },
      back(){
        this.closeDialog('closeDialog');
      },
      //取消操作
      closeDialog() {
        this.$emit('close', { visible: false });
      },
      //初始化所在省份
      async initProvince(){
        let pl = this.createRegionList();
        this.formList.find(item => item.fieldName === 'provinceid').itemList = pl;
      },
      //初始化所在市数据
      async initCity(provinceId,flag = true){
        if(flag){
          //清空市
          this.formList.find(item => item.fieldName === 'cityid').initialValue="";
          this.formList.find(item => item.fieldName === 'cityid').itemList = [];
          //清空县
          this.formList.find(item => item.fieldName === 'districtid').initialValue="";
          this.formList.find(item => item.fieldName === 'districtid').itemList=[];
        }
        if(!provinceId || provinceId==null || typeof(provinceId)=='undefined'){
          return;
        }
        //取省数据
        let rd = this.getRegionData();
        this.cityData = rd[provinceId].children;
        let cl = this.createSubRegionList(this.cityData);
        this.formList.find(item => item.fieldName === 'cityid').itemList = cl;
      },
      //初始化所在县数据
      async initTown(cityId,flag = true){
        if(flag){
          //清空县
          this.formList.find(item => item.fieldName === 'districtid').initialValue="";
          this.formList.find(item => item.fieldName === 'districtid').itemList=[];
        }
        if(!cityId || cityId==null || typeof(cityId)=='undefined'){
          return;
        }
        let td = this.cityData[cityId].children;
        let tl = this.createSubRegionList(td);
        this.formList.find(item => item.fieldName === 'districtid').itemList = tl;
      },

      //初始化所在区数据
      async initDistrict(cityId) {
        if (!cityId || cityId == null || typeof cityId == 'undefined') {
          return;
        }
        let cl = this.district(cityId);
        //初始化区县，清除原值
        let district = this.formList.find(item => item.fieldName === 'districtid');
        district.itemList = cl;
        district.initialValue = '';
      },
      createTopFilterList() {
        return [{//2
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'xsjxhdm',
          initialValue:'',
          placeholder: '经销商代码',
          disabled:true
          },
          {//3
            type: 'INPUT',
            label: '经销商名称',
            fieldName: 'xsjxhmc',
            initialValue: '',
            placeholder: '请输入',
            disabled: true
          },
          {//9
            type: 'SELECT',
            label: '地址性质',
            fieldName: 'xsdzxz',
            placeholder: '请选择',
            initialValue: '',
            itemList: this.createDictList('5001'),
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//9
            type: 'SELECT',
            label: '申请类型',
            fieldName: 'xssqlx',
            placeholder: '请选择',
            initialValue: 50021001,
            disabled: this.type !== 'edit',
            itemList: this.createDictList('5002'),
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//13
            type: 'INPUT',
            label: '联系人',
            fieldName: 'xtlxry',
            placeholder: '请输入',
            initialValue: '',
            maxlength:100,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'blur'
              },
              { max: 100,
                message: '长度最大100字符',
                trigger: 'blur'
              }
            ]
          },
          {//14
            type: 'INPUT',
            label: '联系人电话',
            fieldName: 'xtlxdh',
            placeholder: '请输入',
            initialValue: '',
            maxlength:11,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'blur'
              },
              {
                pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                message: '请填写正确的手机格式',
                trigger: 'blur'
              }
            ]
          },
          {//15
            type: 'INPUT',
            label: '邮箱地址',
            fieldName: 'xsyxdz',
            placeholder: '请输入',
            initialValue: '',
            maxlength:60,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'blur'
              },
              { max: 60,
                message: '长度最大60字符',
                trigger: 'blur'
              },
              {
                type:'email',
                message: '请输入正确的邮箱',
                trigger: 'blur'
              }
            ]
          },
          {//10
            type: 'SELECT',
            label: '省份',
            fieldName: 'provinceid',
            placeholder: '请选择',
            initialValue: "",
            itemList:  [],
            change: (value) => {
              this.initCity(value)
            },
            rules: [{
              required: true,
              message: '必填',
              trigger: 'change'
            }]
          },
          {//11
            type: 'SELECT',
            label: '城市',
            fieldName: 'cityid',
            placeholder: '请选择',
            initialValue: "",
            itemList: [],
            change: (value) => {
              this.initTown(value)
            },
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//12
            type: 'SELECT',
            label: '县区',
            fieldName: 'districtid',
            placeholder: '请选择',
            initialValue: "",
            itemList:  [],
            change: (value) => {
              this.initDistrict(value)
            }
          },
          {
            type: 'SELECT',
            label: '是否有效',
            fieldName: 'xtqybz',
            placeholder: '请选择',
            initialValue: 10041001,
            disabled: true,
            itemList: this.createDictList('1004'),
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'change'
              }
            ]
          },
          {//17
            type: 'INPUT',
            label: '固定电话',
            fieldName: 'xsgddh',
            placeholder: '请输入',
            initialValue: '',
            maxlength:11,
          },
          {//22
            type: 'TEXT_AREA',
            label: '详细地址',
            fieldName: 'xsxxdz',
            placeholder: '请输入',
            initialValue: '',
            maxlength:300,
            selfCols:3,
            rules: [
              {
                required: true,
                message: '必填',
                trigger: 'blur'
              },
              { max: 200,
                message: '长度最大300字符',
                trigger: 'blur'
              }
            ]
          },
          {//22
            type: 'TEXT_AREA',
            label: '驳回原因',
            fieldName: 'xsbhyy',
            placeholder: '请输入',
            initialValue: '',
            maxlength:300,
            hidden:this.type !=='sh',
            selfCols:3,
            rules: [
              { max: 200,
                message: '长度最大200字符',
                trigger: 'blur'
              }
            ]
          },
          {//22
            type: 'TEXT_AREA',
            label: '备注',
            fieldName: 'xtbeiz',
            placeholder: '请输入',
            initialValue: '',
            maxlength:300,
            selfCols:3,
          }
        ]
      },
      createDictList(code, vals = []) {
        vals = Array.isArray(vals) ? vals : [vals];
        let res = [];
        if (_.isObject(this.dict) && Array.isArray(this.dict[code])) {
          res = this.dict[code].map(x => ({
            text: x.codeCnDesc,
            value: x.codeId
          }));
          res = res.filter(x => !vals.includes(x.value));
        }
        return res;
      },
      changeHandle(val) {
        this.saveData=val;
      }
    }
  };
</script>

<style scoped>
</style>
